/*
 * SerialComm.cpp
 *
 *  Created on: 14.10.2008
 *      Author: michael
 */

#include "SerialComm.h"
#include <stdexcept>

SerialComm::SerialComm(const char *device) throw (exception) {
	/**
	 *
	 * Serielle Schnittstelle öffnen
	 *
	 */
	fd = open(device, OPEN_FLAGS);
    if (fd < 0)
		throw runtime_error(OPENING_PORT);
	else {
		//fcntl(fd, F_SETFL, 0);

		/* get the current options */
		fcntl(fd, F_SETFL, 0);
		if (tcgetattr(fd, &tio) != 0)
			throw runtime_error(READING_SETTINGS);

		cfsetispeed(&tio, B19200);            /* setze 19200 bps */
		cfsetospeed(&tio, B19200);
		/* setze Optionen */
		tio.c_cflag &= ~PARENB;               /* kein Paritybit */
		tio.c_cflag &= ~CSTOPB;               /* 1 Stopbit */
		tio.c_cflag &= ~CSIZE;                /* 8 Datenbits */
		tio.c_cflag |= CS8;
		tio.c_cflag |= (CLOCAL | CREAD);      /* CD-Signal ignorieren */
		/* Kein Echo, keine Steuerzeichen, keine Interrupts */
		tio.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
		tio.c_oflag &= ~OPOST;                /* setze "raw" Input */
		tio.c_cc[VMIN]  = 0;                  /* warten auf min. 0 Zeichen */
		tio.c_cc[VTIME] = 10;                 /* Timeout 10 Sekunden */
		tcflush(fd,TCIOFLUSH);
		if (tcsetattr(fd, TCSAFLUSH, &tio) != 0)
			throw runtime_error(WRITING_SETTINGS);
	}
}

SerialComm::~SerialComm() {
    close(fd);
}

void SerialComm::send(unsigned char data[]) throw (exception){
	if (sizeof(data) != DATA_LENGTH)
		throw out_of_range(FALSE_ARRAY_SIZE);

	int rc = write(fd, data, DATA_LENGTH);
	if (rc < 0)
		throw runtime_error(WRITING_DATA);
//	else if (rc != DATA_LENGTH)
//		throw underflow_error(WRITING_DATA);
}

void SerialComm::receive(unsigned char data[]) throw (exception){
	if (sizeof(data) != DATA_LENGTH)
		throw out_of_range(FALSE_ARRAY_SIZE);

	int rc = read(fd, data, DATA_LENGTH);
	if (rc < 0)
		throw runtime_error(READING_DATA);
//	else if (rc != data_length)
//		throw underflow_error(READING_DATA);
}
